# !/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import json
import datetime
from xtls.logger import get_logger

from company_xsb_handler import XsbBaseHandler
from cleaner import clean_str_null

reload(sys)
sys.setdefaultencoding('utf-8')

class HolderHandler(XsbBaseHandler):
    def __init__(self, stock, data, tab_op):
        logger = get_logger(__file__)
        super(HolderHandler, self).__init__(stock, data, tab_op, logger)
        self.tab_name = 'holder'

    def parse(self):
        reasult = []

        if not self.data:
            return reasult

        for single in self.data:
            reasult.append(self.data_transfer(single))

        return reasult

    def data_transfer(self, data):
        db_data = dict()
        db_data['deadline'] = data.get('date', '')  # 截止时间
        db_data['name'] = data.get('name', '')  # 股东名称
        db_data['shares'] = data.get('quantity', '')  # 持股数量(股)
        db_data['proportion'] = data.get('ratio', '')  # 持股比例 小数

        return clean_str_null(db_data)

    def clean_data(self, dirty_data):
        self.cleaner.set_dirty_data(dirty_data)
        return self.cleaner.complete()

    def save_print(self, data):
        for single in data:
            clean_data = self.clean_data(single)
            print json.dumps(clean_data, indent=4)
        # raw_input()

    def save_update(self, data):
        version_num = 1 + self.select_current_version_num(table_name=self.tab_name,
                                                          stock_id=self.stock.id)
        for single in data:
            if not single:
                self.logger.warn('holder has no information %s-%s' % (self.stock.id, self.stock.stock_code))
                return
            if not self.stock.id:
                return

            single_clean = self.clean_data(single)
            single_clean['holderType'] = 'shareholders'
            single_clean['stockId'] = self.stock.id
            single_clean['versionNum'] = version_num
            self.insert_to_db(table_name=self.tab_name, cleaned_data=single_clean)

    def save_insert(self, data):
        if not self.stock.id:
            return
        # print json.dumps(self.stock.__dict__, indent=4)
        # raw_input()
        version_num = self.select_current_version_num(table_name=self.tab_name,
                                                      stock_id=self.stock.id)
        version_num = 1 if version_num == 0 else version_num
        lastest_date = self.select_lastest_date(table_name=self.tab_name,
                                                field_name='deadline',
                                                stock_id=self.stock.id)

        for single in data:
            if not single:
                self.logger.warn('holder has no information %s-%s' % (self.stock.id, self.stock.stock_code))
                return
            single_clean = self.clean_data(single)
            cur_date = single_clean.get('deadline')
            if not self.check_lastest(cur_date, lastest_date):
                continue

            single_clean['holderType'] = 'shareholders'
            single_clean['stockId'] = self.stock.id
            single_clean['versionNum'] = version_num
            self.insert_to_db(table_name=self.tab_name, cleaned_data=single_clean)

# --------------------------------util-------------------------------------------
    def select_lastest_date(self, table_name, field_name, stock_id, version_num=None):
        table_name = 'company_%s' % table_name
        if version_num:
            sql = 'SELECT MAX(%s) FROM %s WHERE stock_id=%s AND version_num=%s'
            sql = sql % (field_name, table_name, '%s', '%s')
            self.cur.execute(sql, (stock_id, version_num))
        else:
            sql = 'SELECT MAX(%s) FROM %s WHERE stock_id=%s'
            sql = sql % (field_name, table_name, '%s')
            self.cur.execute(sql, (stock_id, ))

        lastest_date = self.cur.fetchone()[0]
        return lastest_date if lastest_date else datetime.date(1949, 10, 1)

    def check_lastest(self, cur_date, lastest_date):
        if not cur_date:
            return False
        try:
            res_date = datetime.date(year=int(cur_date[0:4]),
                                     month=int(cur_date[4:6]),
                                     day=int(cur_date[6:]))
        except ValueError:
            return False

        return False if res_date <= lastest_date else True



